<?php

namespace App\Http\Middleware;

use App\Models\Admin\AdminUserRole;
use Closure;
use Illuminate\Support\Facades\Route;

class Rbac
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        //查询用户当前登录用户的权限
        $admin_user = session('admin_user');

        if (!$admin_user) {
            return redirect('/admin/login');
        }
        $id = $admin_user['id'];

        $permissions = AdminUserRole::select('admin_permissions.*')
            ->LeftJoin('admin_role_permission', 'admin_role_permission.role_id', 'admin_user_role.role_id')
            ->LeftJoin('admin_permissions', 'admin_permissions.id', 'admin_role_permission.permission_id')
            ->where('admin_user_role.user_id', $id)
            ->groupBy('admin_permissions.id')
            ->get();
//        dd($permissions);
        /*
                     * SELECT permissions.* FROM role_user
                        LEFT JOIN permission_role ON role_user.role_id = permission_role.role_id
                        LEFT JOIN permissions on permission_role.permission_id=permissions.id
                        where role_user.user_id = 1
                        GROUP BY permissions.id
        */
        $pers = array('admin');
        //dump($current = Route::current()->uri());
        //dump($permissions);
        foreach ($permissions as $permission) {
            $pers[] = $permission->display_name;
        }
//        dd($pers);
        //        //得到数组的结构
        //        foreach ($permissions as $permission) {
        //            //取出来顶级的元素
        //            if ($permission->parent_id == 0) {
        //                foreach ($permissions as $v)
        //                    if ($permission->id == $v->parent_id) {
        //                        $tree[$permission->display_name][] = $v;
        //                    }
        //            }
        //        }
//                dd($tree);

        $current = Route::current()->uri();
        if (!in_array($current, $pers)) {
            return back()->with('mess', '你没有权限访问');
        }
        return $next($request);
    }
}

